package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.io.File;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoFormatBinding;
import flc.ast.dialog.FileNameDialog;
import flc.ast.dialog.FormatConvDialog;
import flc.ast.dialog.FormatDialog;
import flc.ast.dialog.RenameDialog;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaMetadataInfo;
import stark.common.basic.media.video.VideoFormat;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class VideoFormatActivity extends BaseAc<ActivityVideoFormatBinding> {

    private String mVideoPath;

    //选择属性
    private String mSelFormat = "mp4";//选择的格式
    private String mNewName = "";//新的名称
    private String mSelFbl = "";//选择的分辨率
    private String mSelMl = "";//选择的码率
    private String mSelZl = "";//选择的帧率
    private int mOriVideoBitrate;
    private FileNameDialog fileNameDialog;
    private FormatDialog formatDialog;
    private FormatDialog resolutionDialog;
    private FormatDialog codeDialog;
    private FormatDialog frameDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_video_format;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivVideoFormatBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivAddVideo.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.tvTargetFormat.setOnClickListener(this);
        mDataBinding.tvName.setOnClickListener(this);
        mDataBinding.tvResolution.setOnClickListener(this);
        mDataBinding.tvCode.setOnClickListener(this);
        mDataBinding.tvFrame.setOnClickListener(this);
        mDataBinding.ivConvert.setOnClickListener(this);

        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.ivPlay.setSelected(false);
                mp.seekTo(1);
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivAddVideo) {//添加视频
            getVideo();
        } else if (id == R.id.ivPlay) {//播放/暂停
            if (mDataBinding.videoView.isPlaying()) {
                mDataBinding.ivPlay.setImageResource(R.drawable.bf);
                mDataBinding.videoView.pause();
            } else {
                mDataBinding.ivPlay.setImageResource(R.drawable.zanting);
                mDataBinding.videoView.start();
            }
        } else if (id == R.id.tvTargetFormat) {//目标格式
            showFormatDialog();
        } else if (id == R.id.tvName) {//文件名称
            showFileNameDialog();
        } else if (id == R.id.tvResolution) {//分辨率
            showResolutionDialog();
        } else if (id == R.id.tvCode) {//码率
            showCodeDialog();
        } else if (id == R.id.tvFrame) {//帧率
            showFrameDialog();
        } else if (id == R.id.ivConvert) {//立即转换
            startConvert();
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvTargetFormat.setText(mSelFormat);
    }

    private void getVideo() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_video_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        PhotoSelectorBuilder
                                .builder(VideoFormatActivity.this)
                                .mode(PhotoConfig.Mode.VIDEO)
                                .minCount(1)
                                .maxCount(1)
                                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                                    @Override
                                    public void onResult(List<SelectMediaEntity> data) {
                                        if (data != null && data.size() != 0) {
                                            SelectMediaEntity entity = data.get(0);
                                            mVideoPath = entity.getPath();
                                            mDataBinding.tvOriginalFormat.setText(FileUtils.getFileExtension(mVideoPath));
                                            mDataBinding.videoView.setVideoPath(mVideoPath);
                                            mDataBinding.videoView.seekTo(1);
                                            mDataBinding.rlVideo.setVisibility(View.VISIBLE);
                                            mDataBinding.ivAddVideo.setVisibility(View.GONE);
                                            //获取视频码率
                                            getCodeRate();
                                        }
                                    }
                                });
                    }
                }).
                request();
    }

    private void showFileNameDialog() {
        if (fileNameDialog == null) fileNameDialog = new FileNameDialog(mContext);
        fileNameDialog.setListener(new FileNameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                mDataBinding.tvName.setText(name);
                mNewName = name;
            }
        });
        fileNameDialog.show();
    }

    private void showFormatDialog() {
        if (formatDialog == null) {
            formatDialog = new FormatDialog(mContext);
        }
        formatDialog.setType(0);
        formatDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvTargetFormat.setText(name);
                mSelFormat = name;
            }
        });
        formatDialog.show();
    }

    private void showResolutionDialog() {
        if (resolutionDialog == null) {
            resolutionDialog = new FormatDialog(mContext);
        }
        resolutionDialog.setType(1);
        resolutionDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvResolution.setText(name);
                mSelFbl = name;
            }
        });
        resolutionDialog.show();
    }

    private void showCodeDialog() {
        if (codeDialog == null) {
            codeDialog = new FormatDialog(mContext);
        }
        codeDialog.setType(2);
        codeDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvCode.setText(name);
                mSelMl = name;
            }
        });
        codeDialog.show();
    }

    private void showFrameDialog() {
        if (frameDialog == null) {
            frameDialog = new FormatDialog(mContext);
        }
        frameDialog.setType(3);
        frameDialog.setListener(new FormatDialog.IListener() {
            @Override
            public void clickItemName(String name) {
                mDataBinding.tvFrame.setText(name);
                mSelZl = name;
            }
        });
        frameDialog.show();
    }

    private void getCodeRate() {
        RxUtil.create(new RxUtil.Callback<MediaMetadataInfo>() {
            @Override
            public void doBackground(ObservableEmitter<MediaMetadataInfo> emitter) {
                MediaMetadataInfo info = MediaUtil.getMediaMetadataInfo(mVideoPath);
                emitter.onNext(info);
            }

            @Override
            public void accept(MediaMetadataInfo info) {
                if (info != null) {
                    mOriVideoBitrate = info.getBitrate();
                }
            }
        });
    }

    private void startConvert() {
        if (TextUtils.isEmpty(mVideoPath)) {
            ToastUtils.showShort(getString(R.string.please_add_video));
        } else if (TextUtils.isEmpty(mNewName)) {
            ToastUtils.showShort(R.string.please_input_file_name);
        } else if (TextUtils.isEmpty(mSelFbl)) {
            ToastUtils.showShort(R.string.please_sel_fbl);
        } else if (TextUtils.isEmpty(mSelMl)) {
            ToastUtils.showShort(R.string.please_sel_ml);
        } else if (TextUtils.isEmpty(mSelZl)) {
            ToastUtils.showShort(R.string.please_sel_zl);
        } else {
            mDataBinding.ivConvert.setEnabled(false);
            //整理参数
            float fbl = getFbl();
            int ml = getMl();
            String format = getFormat();
            int width = (int) (mDataBinding.videoView.getWidth() * fbl);
            int height = (int) (mDataBinding.videoView.getHeight() * fbl);
            FormatConvDialog dialog = new FormatConvDialog(mContext);
            dialog.videoPath = mVideoPath;
            dialog.newName = mNewName;
            dialog.format = format;
            dialog.width = width;
            dialog.height = height;
            dialog.ml = ml;
            dialog.show();
        }
    }

    //根据选择的格式获取格式后缀
    private String getFormat() {
        String format = VideoFormat.MP4.getSuffix();
        if (mSelFormat.equals(getString(R.string.video_format1))) {
            format = VideoFormat.MP4.getSuffix();
        } else if (mSelFormat.equals(getString(R.string.video_format2))) {
            format = VideoFormat.AVI.getSuffix();
        } else if (mSelFormat.equals(getString(R.string.video_format3))) {
            format = VideoFormat.MKV.getSuffix();
        } else if (mSelFormat.equals(getString(R.string.video_format4))) {
            format = VideoFormat.THREE_GP.getSuffix();
        } else if (mSelFormat.equals(getString(R.string.video_format5))) {
            format = VideoFormat.MOV.getSuffix();
        }
        return format;
    }

    //根据选择的码率获取码率比例
    private int getMl() {
        float mBitrateScale = 1.0f;
        if (mSelMl.equals(getString(R.string.ml_text1))) {
            mBitrateScale = 0.4f;
        } else if (mSelMl.equals(getString(R.string.ml_text2))) {
            mBitrateScale = 0.6f;
        } else if (mSelMl.equals(getString(R.string.ml_text3))) {
            mBitrateScale = 0.8f;
        } else if (mSelMl.equals(getString(R.string.ml_text4))) {
            mBitrateScale = 1.0f;
        }
        return (int) (mOriVideoBitrate * mBitrateScale);
    }


    //根据选择的分辨率获取分辨率比例
    private float getFbl() {
        float mResolutionScale = 1.0f;
        if (mSelFbl.equals(getString(R.string.fbl_text1))) {
            mResolutionScale = 1.0f;
        } else if (mSelFbl.equals(getString(R.string.fbl_text2))) {
            mResolutionScale = 0.8f;
        } else if (mSelFbl.equals(getString(R.string.fbl_text3))) {
            mResolutionScale = 0.6f;
        } else if (mSelFbl.equals(getString(R.string.fbl_text4))) {
            mResolutionScale = 0.5f;
        }
        return mResolutionScale;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivPlay.setImageResource(R.drawable.bf);
        mDataBinding.videoView.pause();
    }

}